// 创建一个Web服务器
// 处理资源请求 1.index.html 2.js 3.vue
const Koa = require('koa')
const fs = require('fs')
const path = require('path')
const compilerSFC = require('@vue/compiler-sfc')
const compilerDOM = require('@vue/compiler-dom')


const app = new Koa()

app.use(ctx => {
    const { url, query } = ctx.request
    if (url === '/'){
            // 加载html
    ctx.type = 'text/html'
    ctx.body = fs.readFileSync('./index.html', 'utf-8')
    }else if (url.endsWith('.js')){
        const p = path.join(__dirname, url)
        ctx.type = 'application/javascript'
        ctx.body = rewiriteImport(fs.readFileSync(p, 'utf-8'))
    }else if (url.startsWith('/@modules/')){
        let moduleName = url.replace('/@modules/', '')
        // node_modules目录中找裸模块
        const prefix = path.join(__dirname, './node_modules', moduleName)
        // package.json中获取module字段
        module = require(prefix + '/package.json').module
        const filePath = path.join(prefix, module)
        const ret = fs.readFileSync(filePath, 'utf-8')
        ctx.type = 'application/javascript'
        ctx.body = rewiriteImport(ret)
    } else if (url.indexOf('.vue') > -1){
        
        const p = path.join(__dirname, url.split('?')[0])
        const ret = compilerSFC.parse(fs.readFileSync(p, 'utf-8'))
        console.log(ret);
        console.log(url, !query, query);
        // SFC请求
        // 读取vue文件， 解析为js
        if (!query.type){
            // 获取脚本部分的内容
            const scriptContent = ret.descriptor.script.content
            // 替换默认导出为一个常量， 方便后续修改
            const script = scriptContent.replace('export default ', 'const __script = ')
            ctx.type = 'text/javascript'
            ctx.body = `
                ${rewiriteImport(script)}
                // 解析tpl
                import {render as __render } from '${url}?type=template'
                __script.render = __render
                export default __script
            ` 
        }else if (query.type === 'template'){
            
            const tpl = ret.descriptor.template.content
            // 编译为render
            const render = compilerDOM.compile(tpl, {mode:'module'}).code
            ctx.type="application/javascript"
            ctx.body = rewiriteImport(render)
        }
    }

})

// 裸模块地址重写
// import vue from 'vue'
// import vue from '/@modules/vue
function rewiriteImport(content){
    return content.replace(/from ['"](.*)['"]/g, (p, p1) => {
        if (p1.startsWith('./') || p1.startsWith('../')|| p1.startsWith('/')){
            return `from '${p1}'`
        }else {
            // 裸模块替换
            return `from '/@modules/${p1}'`
        }  
    })
}

app.listen('3001', ()=> {
    console.log('服务器搭建成功');
})